//
//  MyTravelsVC.m
//  SelfDrivingTravelling-IOS
//
//  Created by Teplot_01 on 16/8/5.
//  Copyright © 2016年 Teplot_01. All rights reserved.
//

#import "MyTravelsVC.h"
#import "MyTravelsCell.h"
#import "TravelsDetailVC.h"
#import "PublicNewsViewController.h"
@interface MyTravelsVC ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@end

@implementation MyTravelsVC
{
    UITableView *_tableView;
    NSInteger _currentPage;
    //请求下来的字典
    NSDictionary *_responseDic;
    //请求下来的数组
    NSMutableArray *_responseArr;
}
- (void)viewWillAppear:(BOOL)animated{
    _currentPage = 1;
    [self reqsetForMyTravelsCurrentPage:_currentPage isFirst:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"我的游记";
    _responseArr = [NSMutableArray array];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tianjia"] style:UIBarButtonItemStylePlain target:self action:@selector(createTravels)];
    self.navigationItem.backBarButtonItem= [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    [self initTableView];
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
}
#pragma - mark RequsetForMyTravels
- (void)reqsetForMyTravelsCurrentPage:(NSInteger)currentPage isFirst:(BOOL)isFirst{
    //参数
    NSDictionary *parameters = @{
                                 @"clubId":[NSString readToNSDefaultsWithKey:kClubId],
                                 @"userId":[NSString readToNSDefaultsWithKey:kId],
                                 @"pageNum": @(_currentPage),
                                 @"pageSize":@"10",
                                 };
    [SVProgressHUD showWithStatus:@"请求中"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://115.28.152.130/tour/v1/travel/list.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
        [_tableView.mj_header endRefreshing];
        _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@>>>>",_responseDic);
        NSArray *temp = _responseDic[@"list"];
        NSString *error = _responseDic[@"code"];
        if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
        }else{
            if (isFirst) {
                if (temp.count == 0) {
                    [SVProgressHUD showImage:nil status:@"暂无数据"];
                }
                [_responseArr removeAllObjects];
            }
            [_responseArr addObjectsFromArray:temp];
            
            if (temp.count < 10) {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                [_tableView.mj_footer endRefreshing];
            }
            //请求成功
            [_tableView reloadData];
            [SVProgressHUD dismiss];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"请求游记列表失败"];
        [SVProgressHUD dismiss];
    }];
}
- (void)initTableView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [self refreshDown];
    [self refreshLoadMore];
}
//下拉刷新
- (void)refreshDown{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage = 1;
        [self reqsetForMyTravelsCurrentPage:_currentPage isFirst:YES];
    }];
}
//上提加载更多
- (void)refreshLoadMore{
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _currentPage++;
        [self reqsetForMyTravelsCurrentPage:_currentPage isFirst:NO];
    }];
}
#pragma - mark UITabelView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _responseArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyTravelsCell *cell = [[NSBundle mainBundle]loadNibNamed:@"MyTravelsCell" owner:nil options:nil][0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.title.text = _responseArr[indexPath.row][@"title"];
    cell.city.text = _responseArr[indexPath.row][@"author"];
    NSString *timeStr = _responseArr[indexPath.row][@"createTime"];
    timeStr = [timeStr substringToIndex:10];
    cell.beginTime.text = timeStr;
    NSString *iconStr = _responseArr[indexPath.row][@"userPhoto"];
    cell.icon.layer.masksToBounds = YES;
    cell.icon.layer.cornerRadius = 5;
    [cell.icon sd_setImageWithURL:[NSURL URLWithString:iconStr] placeholderImage:[UIImage imageNamed:@"head_portrait"]];
    NSString *urlStr = _responseArr[indexPath.row][@"thumbs"];
    if (urlStr.length < 50) {
        urlStr = nil;
    }else{
        urlStr = [urlStr substringFromIndex:1];
        urlStr = [urlStr substringToIndex:83];
    }
    [cell.image sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"picture_8"]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TravelsDetailVC *vc = [[TravelsDetailVC alloc]init];
    vc.htmlUrlStr = _responseArr[indexPath.row][@"htmlUrl"];
    vc.travelsId = _responseArr[indexPath.row][@"id"];
    vc.travelsName = _responseArr[indexPath.row][@"title"];
    vc.travelTime = _responseArr[indexPath.row][@"createTime"];
    vc.travelIcon = _responseArr[indexPath.row][@"userPhoto"];
    vc.travelAuthor = _responseArr[indexPath.row][@"author"];
    [self.navigationController pushViewController:vc animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        //先把需要删除的游记id上传服务器
        NSString *idStr = _responseArr[indexPath.row][@"id"];
        NSDictionary *parameters = @{
                                     @"travelId": idStr,
                                     };
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer=[AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        [manager POST:@"http://115.28.152.130/tour/v1/travel/delete.action" parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
            _responseDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@>>>>",_responseDic);
            _responseArr = _responseDic[@"list"];
            NSString *error = _responseDic[@"code"];
            if (![_responseDic[@"code"] isEqualToString:@"0000"]) {
                [SVProgressHUD showErrorWithStatus:[NSString errorStringWithCode:error]];
            }else{
                //删除请求成功后，再次请求新的数据
                _responseArr = [NSMutableArray array];
                _currentPage = 1;
                [self reqsetForMyTravelsCurrentPage:_currentPage isFirst:YES];
            }
            
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"删除游记失败"];
        }];
        
    }
}
- (void)createTravels{
    PublicNewsViewController *vc = [[PublicNewsViewController alloc]init];
    [@"" saveToNSDefaultsWithKey:kPAID];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
